import 'dart:io';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mesh/function/utils/mesh_url.dart';
import 'package:mesh/function/widgets/border_widget.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import '../states/team_conversation_state.dart';
import '../states/user_state.dart';
import '../widgets/animated_tap_widget.dart';
import '../widgets/toast_widget.dart';

/// 创建群聊弹窗组件
class CreateTeamDialog extends StatefulWidget {
  const CreateTeamDialog({super.key});

  /// 显示创建群聊弹窗
  static Future<void> show(BuildContext context) {
    return showGeneralDialog<void>(
      context: context,
      barrierDismissible: true,
      barrierLabel: '',
      barrierColor: Colors.black.withOpacity(0.5),
      transitionDuration: const Duration(milliseconds: 300),
      pageBuilder: (
        BuildContext context,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
      ) {
        return const CreateTeamDialog();
      },
      transitionBuilder: (
        BuildContext context,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
        Widget child,
      ) {
        return FadeTransition(
          opacity: animation,
          child: ScaleTransition(
            scale: Tween<double>(begin: 0.8, end: 1.0).animate(
              CurvedAnimation(parent: animation, curve: Curves.easeOutBack),
            ),
            child: child,
          ),
        );
      },
    );
  }

  @override
  State<CreateTeamDialog> createState() => _CreateTeamDialogState();
}

class _CreateTeamDialogState extends State<CreateTeamDialog> {
  final TextEditingController _locationController = TextEditingController();
  final TextEditingController _timeController = TextEditingController();
  String? _selectedImagePath;

  @override
  void dispose() {
    _locationController.dispose();
    _timeController.dispose();
    super.dispose();
  }

  /// 选择图片
  Future<void> _selectImage() async {
    try {
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        context,
        pickerConfig: const AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        final asset = assets.first;
        final file = await asset.file;
        if (file != null) {
          // 复制图片到本地目录
          final localPath = await _copyImageToLocal(file);
          setState(() {
            _selectedImagePath = localPath;
          });
        }
      }
    } catch (e) {
      ToastWidget.showError('Failed to select image');
    }
  }

  /// 复制图片到本地目录
  Future<String> _copyImageToLocal(File imageFile) async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final imagesDir = Directory(path.join(directory.path, 'team_images'));

      // 创建目录（如果不存在）
      if (!await imagesDir.exists()) {
        await imagesDir.create(recursive: true);
      }

      // 生成唯一文件名
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final extension = path.extension(imageFile.path);
      final fileName = 'team_$timestamp$extension';
      final localPath = path.join(imagesDir.path, fileName);

      // 复制文件
      await imageFile.copy(localPath);
      return localPath;
    } catch (e) {
      throw Exception('Failed to copy image: $e');
    }
  }

  /// 创建群聊
  void _createTeam() {
    // 验证输入
    if (_locationController.text.trim().isEmpty) {
      ToastWidget.showError('Please enter location');
      return;
    }

    if (_timeController.text.trim().isEmpty) {
      ToastWidget.showError('Please enter time');
      return;
    }

    if (_selectedImagePath == null) {
      ToastWidget.showError('Please upload an image');
      return;
    }

    // 获取当前用户
    final currentUser = UserState.getCurrentUserInfo();
    if (currentUser == null) {
      ToastWidget.showError('User not logged in');
      return;
    }

    // 创建群聊
    final success = TeamConversationState.createTeam(
      groupName: 'Play Together',
      groupDescription:
          'Let\'s play together at ${_locationController.text.trim()}',
      location: _locationController.text.trim(),
      time: _timeController.text.trim(),
      groupCoverImage: _selectedImagePath!,
      creatorId: currentUser.userId,
    );

    if (success) {
      Navigator.of(context).pop();
      ToastWidget.showSuccess('Team created successfully!');
    } else {
      ToastWidget.showError('Failed to create team');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: SizedBox(
          width: double.infinity,
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              // 装饰图片 - 在 z 轴下方
              Positioned(
                top: -90.h, // 向上位移，露出一半
                right: 20.w, // 水平居中
                left: 20.w,
                child: Image.asset(
                  'assets/images/sun.png',
                  width: 160.w,
                  height: 160.w,
                ),
              ),

              // 主要内容容器
              Container(
                width: double.infinity,
                decoration: BoxDecoration(
                  color: const Color(0xFF663507),
                  borderRadius: BorderRadius.circular(24.r),
                ),
                child: Stack(
                  children: [
                    // 右上角关闭按钮
                    Positioned(
                      top: 2.w,
                      right: 2.w,
                      child: AnimatedTapButton(
                        onTap: () => Navigator.of(context).pop(),
                        child: Container(
                          width: 32.w,
                          height: 32.w,
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.1),
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            Icons.close,
                            color: Colors.white,
                            size: 20.w,
                          ),
                        ),
                      ),
                    ),

                    // 内容
                    Padding(
                      padding: EdgeInsets.all(24.w),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          // 标题
                          Text(
                                'Create A Team To Play Together',
                                style: TextStyle(
                                  decoration: TextDecoration.none,
                                ),
                              )
                              .fontSize(18.sp)
                              .textColor(Colors.white)
                              .fontWeight(FontWeight.w700)
                              .fontFamily(
                                GoogleFonts.quicksand(
                                  fontWeight: FontWeight.w700,
                                ).fontFamily,
                              )
                              .textAlignment(TextAlign.center),

                          SizedBox(height: 24.h),

                          // 位置输入
                          Row(
                            children: [
                              Image.asset(
                                'assets/images/location.png',
                                width: 24.w,
                                height: 24.w,
                              ),
                              SizedBox(width: 10.w),
                              Expanded(
                                child: Container(
                                  height: 44.h,
                                  decoration: BoxDecoration(
                                    color: const Color(0xFF855A12),
                                    borderRadius: BorderRadius.circular(4.r),
                                  ),
                                  child: Center(
                                    child: TextField(
                                      controller: _locationController,
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 12.sp,
                                        fontFamily:
                                            GoogleFonts.quicksand(
                                              fontWeight: FontWeight.w400,
                                            ).fontFamily,
                                      ),
                                      decoration: InputDecoration(
                                        hintText:
                                            'Enter The Address Where You Want To Play',
                                        hintStyle: TextStyle(
                                          color: Colors.white.withOpacity(0.6),
                                          fontSize: 12.sp,
                                          fontFamily:
                                              GoogleFonts.quicksand(
                                                fontWeight: FontWeight.w400,
                                              ).fontFamily,
                                        ),
                                        border: InputBorder.none,
                                        contentPadding: EdgeInsets.symmetric(
                                          horizontal: 16.w,
                                          vertical: 12.h,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),

                          SizedBox(height: 16.h),

                          // 时间输入
                          Row(
                            children: [
                              Image.asset(
                                'assets/images/time.png',
                                width: 24.w,
                                height: 24.w,
                              ),
                              SizedBox(width: 10.w),
                              Expanded(
                                child: Container(
                                  height: 44.h,
                                  decoration: BoxDecoration(
                                    color: const Color(0xFF855A12),
                                    borderRadius: BorderRadius.circular(4.r),
                                  ),
                                  child: Center(
                                    child: TextField(
                                      controller: _timeController,
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 12.sp,
                                        fontFamily:
                                            GoogleFonts.quicksand(
                                              fontWeight: FontWeight.w400,
                                            ).fontFamily,
                                      ),
                                      decoration: InputDecoration(
                                        hintText: 'Enter The Time To Play',
                                        hintStyle: TextStyle(
                                          color: Colors.white.withOpacity(0.6),
                                          fontSize: 12.sp,
                                          fontFamily:
                                              GoogleFonts.quicksand(
                                                fontWeight: FontWeight.w400,
                                              ).fontFamily,
                                        ),
                                        border: InputBorder.none,
                                        contentPadding: EdgeInsets.symmetric(
                                          horizontal: 16.w,
                                          vertical: 12.h,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),

                          SizedBox(height: 20.h),

                          // 图片上传区域
                          GestureDetector(
                            onTap: _selectImage,
                            child: Container(
                              width: 130.w,
                              height: 144.h,
                              decoration: BoxDecoration(
                                color: const Color(0xFF854C14),
                                borderRadius: BorderRadius.circular(12.r),
                              ),
                              child:
                                  _selectedImagePath != null
                                      ? ClipRRect(
                                        borderRadius: BorderRadius.circular(
                                          12.r,
                                        ),
                                        child: Image.file(
                                          File(_selectedImagePath!),
                                          fit: BoxFit.cover,
                                        ),
                                      )
                                      : Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Icon(
                                            Icons.image_outlined,
                                            color: const Color(0xFFFF8A3C),
                                            size: 32.w,
                                          ),
                                          SizedBox(height: 8.h),
                                          Text(
                                                'Upload Image',
                                                style: TextStyle(
                                                  decoration:
                                                      TextDecoration.none,
                                                ),
                                              )
                                              .fontSize(14.sp)
                                              .textColor(
                                                Colors.white.withOpacity(0.6),
                                              )
                                              .fontFamily(
                                                GoogleFonts.quicksand(
                                                  fontWeight: FontWeight.w400,
                                                ).fontFamily,
                                              ),
                                        ],
                                      ),
                            ),
                          ),

                          SizedBox(height: 20.h),

                          AnimatedTapButton(
                            onTap: _createTeam,
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(14.r),
                              child: BackdropFilter(
                                filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
                                child: Container(
                                  width: 208.w,
                                  height: 44.h,
                                  decoration: BoxDecoration(
                                    color: const Color(0x33FF8A3C),
                                    borderRadius: BorderRadius.circular(14.r),
                                    border: Border.all(
                                      color: Colors.white.withOpacity(0.4),
                                      width: 1.w,
                                    ),
                                  ),
                                  child: Center(
                                    child: Text(
                                          'Release',
                                          style: TextStyle(
                                            decoration: TextDecoration.none,
                                          ),
                                        )
                                        .fontSize(16.sp)
                                        .textColor(Colors.white)
                                        .fontWeight(FontWeight.w600)
                                        .fontFamily(
                                          GoogleFonts.quicksand(
                                            fontWeight: FontWeight.w600,
                                          ).fontFamily,
                                        ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                          SizedBox(height: 12.h),

                          Column(
                            children: [
                              GestureDetector(
                                onTap: () => MeshUrl.launchEula(),
                                child: Text(
                                  'EULA',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 15.sp,
                                    fontWeight: FontWeight.w500,
                                    fontFamily:
                                        GoogleFonts.quicksand(
                                          fontWeight: FontWeight.w500,
                                        ).fontFamily,
                                    decoration: TextDecoration.underline,
                                    decorationColor: Colors.white,
                                  ),
                                ),
                              ),
                            ],
                          ).alignCenter(),
                        ],
                      ),
                    ),
                  ],
                ),
              ).configBorderWidget(
                borderRadius: 24.r,
                borderColor: Colors.white.withOpacity(0.7),
                borderWidth: 1.w,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
